
var gl;
var points;

window.onload = function init()
{
    var canvas = document.getElementById( "gl-canvas" );
    
    gl = WebGLUtils.setupWebGL( canvas );
    if ( !gl ) { alert( "WebGL isn't available" ); }

    console.log("hello world");
    //var vertices = new Float32Array([-1, -1, 0, 1, 1, -1]);
    var vertices = [
        vec2(-0.5, -0.5), 
        vec2(-0.5, 0.5), 
        vec2(0.5, 0.5),
        vec2(0.5, -0.5)
        ];
        
    var vertex_color = [
        1.0, 0.0, 0.0, 1.0,
        0.0, 1.0, 0.0, 1.0,
        0.0, 0.0, 1.0, 1.0
    ];

    //  Configure WebGL

    gl.viewport( 0, 0, canvas.width, canvas.height );
    gl.clearColor( 1.0, 1.0, 1.0, 1.0 );
    
    //  Load shaders and initialize attribute buffers
    
    var program = initShaders( gl, "vertex-shader", "fragment-shader" );
    gl.useProgram( program );
    
    // Load the data into the GPU
    

     var bufferId = gl.createBuffer();
     gl.bindBuffer( gl.ARRAY_BUFFER, bufferId );
     gl.bufferData( gl.ARRAY_BUFFER, flatten(vertices), gl.STATIC_DRAW );
    
    // 获取html中的attribute对象
    var vPosition = gl.getAttribLocation( program, "vPosition" );
    var color = gl.getAttribLocation(program, 'color');
    
    gl.vertexAttribPointer( vPosition, 2, gl.FLOAT, false, 0, 0 );
    gl.enableVertexAttribArray( vPosition );
    
    /*
    var position_vbo = create_vbo(vertices);
    var color_vbo = create_vbo(vertex_color);
    
    // Associate out shader variables with our data buffer
    // buffer绑定(位置情报)
    gl.bindBuffer(gl.ARRAY_BUFFER, position_vbo);
    
    gl.vertexAttribPointer( vPosition, 2, gl.FLOAT, false, 0, 0 );
    gl.enableVertexAttribArray( vPosition );
    
    gl.bindBuffer(gl.ARRAY_BUFFER, color_vbo);
    //gl.enableVertexAttribArray(color);
    //gl.vertexAttribPointer(color, 4, gl.Float, false, 0, 0);
    */
    
    

    render();
};

function create_vbo(data) {
    // 生成缓存对象
    var vbo = gl.createBuffer();
    
    // 绑定缓存
    gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
    
    // 向缓存中写入数据
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl.STATIC_DRAW);
    
    // 将绑定的缓存设为无效
    gl.bindBuffer(gl.ARRAY_BUFFER, null);
    
    return vbo;
}


function render() {
    gl.clear( gl.COLOR_BUFFER_BIT );
    // gl.drawArrays( gl.TRIANGLES, 0, 3 );
    gl.drawArrays( gl.TRIANGLE_FAN, 0, 4);
}
